﻿/*
   This source code is offered under the Microsoft Public License (Ms-PL) which is outlined as follows:

   Microsoft Public License (Ms-PL)
   This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.

   1. Definitions
   The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
   A "contribution" is the original software, or any additions or changes to the software.
   A "contributor" is any person that distributes its contribution under this license.
   "Licensed patents" are a contributor's patent claims that read directly on its contribution.

   2. Grant of Rights
   (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
   (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.

   3. Conditions and Limitations
   (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
   (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
   (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
   (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
   (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
 */
using System.Collections.Generic;
using System.Threading;
using System;

using RenewalProjects.Libraries.SharedCode;

namespace RenewalProjects.Libraries.Wcf.EasyProxy.Pools
{
	/// <summary>
	/// A generic list-based pool mechanism where you have a pool of
	/// resource items that needs to be managed.
	/// </summary>
	public sealed class ResourceListPool<TResource>: IResourceItemProvider<TResource>
		where TResource : class, IResourceItem
	{
		private const float DEFAULT_POOL_REFILL_THRESHOLD = 75.0f;
		private const int DEFAULT_MAX_ITEMS = 10;

		private readonly object _poolRefreshLock = new object();
		private volatile IList<TResource> _poolItems;
		private Func<TResource> _resourceItemFactory;
		private int _maxItems;
		private float _poolRefillThreshold = DEFAULT_POOL_REFILL_THRESHOLD;

		/// <summary>
		/// Constructor. Sets up a default of 10 items.
		/// </summary>
		public ResourceListPool()
			: this(DEFAULT_MAX_ITEMS)
		{
		}

		/// <summary>
		/// Constructor. Sets up a number of items.
		/// </summary>
		/// <param name="maxItems">Maximum amount of items in pool.</param>
		public ResourceListPool(int maxItems)
		{
			if (maxItems < 1)
			{
				throw new ArgumentOutOfRangeException("maxItems");
			}

			_maxItems = maxItems;
		}

		/// <summary>
		/// Threshold (percentage) of unusable or
		/// expired items before pool gets refilled.
		/// </summary>
		public float ResourceRefillThreshold
		{
			get { return _poolRefillThreshold; }
			set
			{
				if (value < 1.0f || value > 100.0f)
				{
					throw new InvalidOperationException(
						"Cannot have pool refill threshold below 1% or above 100%");
				}

				_poolRefillThreshold = value;
			}
		}

		/// <summary>
		/// Delegate used to (re)create items.
		/// </summary>
		public Func<TResource> ResourceItemFactory
		{
			get { return _resourceItemFactory; }
			set
			{
				if (value == null)
				{
					throw new InvalidOperationException("Cannot set Item factory to null");
				}

				_resourceItemFactory = value;
			}
		}

		/// <summary>
		/// Replenishes resource item pool.
		/// </summary>
		public void RefreshResources()
		{
			if (ResourceItemFactory == null)
			{
				throw new InvalidOperationException(
					"Pool being refreshed without specified Item Factory");
			}

			// Ensure only 1 thread performs this operation
			// as only 1 is needed.
			if (Monitor.TryEnter(_poolRefreshLock))
			{
				try
				{
					if (_poolItems == null)
					{
						List<TResource> items = new List<TResource>(_maxItems);
						for (int i = 0; i < _maxItems; i++)
						{
							TResource newItem = ResourceItemFactory();
							items.Add(newItem);
						}

						_poolItems = items;
					}
					else
					{
						ReplenishUnusableItems();
					}
				}
				finally
				{
					Monitor.Exit(_poolRefreshLock);
				}
			}
		}

		/// <summary>
		/// Find a resource item that is usable.
		/// </summary>
		/// <returns>
		/// Null if none of the items are available,
		/// otherwise it returns an instance thereof.
		/// </returns>
		/// <remarks>
		/// If none is available and a refresh is performed
		/// it will not obtain an available item. It does
		/// a one-pass on the list of resources. You may
		/// need to try again.
		/// </remarks>
		public TResource GetAvailableResource()
		{
			if (_poolItems == null)
			{
				RefreshResources();
			}

			if (_poolItems != null)
			{
				int inactiveCount = 0;

				for (int i = 0; i < _poolItems.Count; i++)
				{
					TResource item = _poolItems[i];

					if (item == null)
					{
						inactiveCount++;
					}
					else
					{
						if (Monitor.TryEnter(item))
						{
							try
							{
								if (!item.InUse)
								{
									if (DistinguishItemUsage(item, i, ref inactiveCount))
									{
										Logging.Debug(
											"Thread {0} : Aquired item in pool [index: {1}]",
											Thread.CurrentThread.ManagedThreadId,
											i);
										return item;
									}
								}
							}
							finally
							{
								Monitor.Exit(item);
							}
						}
					}
				}

				if (PoolRequiresRefill(inactiveCount))
				{
					RefreshResources();
				}
			}

			Logging.Debug("Thread {0} : Didn't find any item in pool", Thread.CurrentThread.ManagedThreadId);
			return null;
		}

		private bool PoolRequiresRefill(int inactiveCount)
		{
			return ((_maxItems - inactiveCount) / (float)_maxItems) * 100.0f <= ResourceRefillThreshold;
		}

		private void ReplenishUnusableItems()
		{
			for (int i = 0; i < _maxItems; i++)
			{
				TResource curItem = _poolItems[i];
				if (curItem == null)
				{
					TResource newItem = ResourceItemFactory();
					_poolItems[i] = newItem;
				}
				else
				{
					// We let this thread wait till this
					// item is free to make sure it gets
					// replenished if expired.
					lock (curItem)
					{
						if (curItem.CheckItemExpiry())
						{
							curItem.DrainItem();

							TResource newItem = ResourceItemFactory();
							_poolItems[i] = newItem;
						}
					}
				}
			}
		}

		private bool DistinguishItemUsage(TResource item, int poolIndex, ref int inactiveCount)
		{
			if (item.CheckItemExpiry())
			{
				inactiveCount++;
				item.InUse = false;
				item.DrainItem();
				_poolItems[poolIndex] = null;
			}
			else
			{
				item.InUse = true;
				return true;
			}

			return false;
		}
	}
}